package com.hzw.saas.common.security.config;

import com.hzw.saas.common.security.token.SaasTokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;

import java.util.Collections;

/**
 * @author zzl
 * @since 12/21/2020
 */
@Configuration
@RequiredArgsConstructor
public class TokenConfig {
    private final UserDetailsService userDetailsService;
    private final TokenStore tokenStore;
    private final TokenEnhancer tokenEnhancer;

//    远程token校验（用户中心）
//    @Bean
//    public ResourceServerTokenServices resourceServerTokenServices() {
//        return new RemoteUserTokenService("localhost:8080/saas/oauth2/check_token");
//    }

    /**
     * 解析Token的业务方法
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public SaasTokenService tokenServices() {
        SaasTokenService tokenServices = new SaasTokenService();
        tokenServices.setTokenStore(tokenStore);
        //支持刷新token
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setReuseRefreshToken(true);
        tokenServices.setTokenEnhancer(tokenEnhancer);
        addUserDetailsService(tokenServices);
        return tokenServices;
    }

    private void addUserDetailsService(SaasTokenService tokenServices) {
        PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
        provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(userDetailsService));
        tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider)));
    }

}
